#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "Log.hpp"

Log lg;
const int backlog = 10;

enum
{
    SOCKETERR = 2,
    BINDERR,
    LISTENERR
};

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

public:
    void Socket()
    {
        _socket = socket(AF_INET, SOCK_STREAM, 0);
        if (_socket < 0)
        {
            lg(Fatal, "socket error , %d, %s", errno, strerror(errno));
            exit(SOCKETERR);
        }
        int opt = 1;
        setsockopt(_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }
    void Bind(const uint16_t &port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);

        if (bind(_socket, (const sockaddr *)&local, len) < 0)
        {
            lg(Fatal, "bind error, %d, %s", errno, strerror(errno));
            exit(BINDERR);
        }
    }

    void Listen()
    {
        if (listen(_socket, backlog) < 0)
        {
            lg(Fatal, "listen error, %d, %s", errno, strerror(errno));
            exit(LISTENERR);
        }
    }

    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        socklen_t len = sizeof(peer);
        int newfd = accept(_socket, (sockaddr *)&peer, &len);
        if (newfd < 0)
        {
            lg(Warning, "accept error, %d, %s", errno, strerror(errno));
            return -1;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &(peer.sin_addr), ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(peer.sin_port);

        return newfd;
    }

    bool Connect(const uint16_t &port, const std::string &ip)
    {
        struct sockaddr_in peer;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));
        socklen_t len = sizeof(peer);
        int n = connect(_socket, (const sockaddr *)&peer, len);
        if (n == -1)
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }
    void Close()
    {
        close(_socket);
    }

    int Fd()
    {
        return _socket;
    }

private:
    int _socket;
};
